<?php

namespace App\Api\Controllers;

use Illuminate\Http\Request;
use phpDocumentor\Reflection\Types\Self_;

class CommonController extends BaseController
{
    const UPLOAD_ALLOW_MODULE = ['goods', 'complaint', 'review'];
    const UPLOAD_ALLOW_TYPE = ['jpg',
        'jpeg',
        'png',
        'gif',
        'bmp',
        'JPG',
        'JPEG',
        'PNG',
        'GIF',
        'BMP'
    ];

    // 图片上传
    public function upload(Request $request)
    {
        $module = $request->post('module');
        if (!in_array($module, self::UPLOAD_ALLOW_MODULE)) {
            return Error(80001, '不支持的模块名称');
        }
        if (!$request->hasFile("file")) {
            return Error(80001, '请选择上传文件');
        }
        $dir  = "/image/{$module}/";
        if (!file_exists(public_path($dir))) {
            mkdir(public_path($dir), 0777, true);
            chmod(public_path($dir), 0777);
        }

        $file = $request->file('file');
        $ext  = $file->getClientOriginalExtension();     // 扩展名
        if (!in_array(strtolower($ext), self::UPLOAD_ALLOW_TYPE)) {
            return Failed(10002, ["File" => "CommonController", "line" => __LINE__, "allow_ext" => self::UPLOAD_ALLOW_TYPE]);
        }
        $filename = time() . "." . strtolower($ext);
        try {
            $file->move(public_path($dir), $filename);
        } catch (\Exception $exception) {
            dd($exception->getCode());
        } catch (\Throwable $e) {
            dd($e->getCode(), $e->getMessage());
        }
        return $this->success(200, "文件上传成功", ['file_path' => $dir . $filename]);
    }

}
